import { ref, reactive, shallowRef } from 'vue';
import echarts from '@/echarts';
import { EChartsOption } from 'echarts';
import { EChartsType } from 'echarts/core';
import type { LineBarChartType, MuSelectValueType } from '../data';

import { getHtmlFontPX, handleChartResize } from '@/utils/base';
import { useAutoTooltip } from '@/utils/echartsAutoTooltip';
import ThemeColor from '@/themeColor';
import { colorList } from '../config';

export default function (props?: {
  showHandler?: (visible: boolean, type: number, selectValue: MuSelectValueType) => void;
  type: number;
}): LineBarChartType {
  const chartRef = shallowRef<EChartsType>();
  const container = ref<HTMLDivElement | undefined>();
  const chart = reactive<LineBarChartType['chart']>({
    selectValue: [4],
    initChart,
    resizeChart
  });
  let chartData = {
    categories: [],
    ratioData: [],
    countOne: [],
    countTwo: [],
    countThree: []
  };

  /**
   * @returns 返回option配置
   */
  function getOption() {
    const option: EChartsOption = {
      color: colorList,
      textStyle: {
        color: ThemeColor.chartFontColor
      },

      tooltip: {
        confine: true,
        axisPointer: {
          lineStyle: {
            width: 2,
            color: '#ffeb7b'
          }
        },
        className: 'tooltip-review',
        formatter: (params: any) => {
          let resStr: string = `<div>${params[0].axisValueLabel}</div>`;
          let preIndex = 0;
          chartData.categories.some((category: string, index: number) => {
            if (category === resStr) {
              preIndex = index;
            }
          });
          params[0].value = chartData.ratioData[preIndex] + '%'; // 换成比率
          params.forEach((item: any) => {
            resStr += `
            <div class="tooltip-item">
              <div class="tooltip-label-icon">
                <span class="tooltip-icon" style="background-color: ${item.color.colorStops ? '#4992ff' : item.color}"></span>
                <span class="tooltip-label">${item.seriesName}：</span>
              </div>
              <span class="tooltip-value">${item.value}</span>
            </div>
            `;
          });
          return resStr;
        },
        // 通过坐标轴来触发
        trigger: 'axis',
        textStyle: {
          fontSize: getHtmlFontPX(0.75)
        }
      },
      // containLabel 为 true 的时候：
      // grid.left grid.right grid.top grid.bottom grid.width grid.height 决定的是包括了坐标轴标签在内的所有内容所形成的矩形的位置。
      // 这常用于『防止标签溢出』的场景，标签溢出指的是，标签长度动态变化时，可能会溢出容器或者覆盖其他组件。
      grid: {
        left: '3%',
        right: '140px',
        bottom: '3%',
        top: '6px',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        axisTick: {
          show: false
        },
        axisLine: {
          show: false,
          lineStyle: {
            color: '#DCE2E8'
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: ThemeColor.chartLineColor
          }
        }
      },
      yAxis: {
        type: 'category',
        axisLabel: {
          fontSize: getHtmlFontPX(0.75)
        },
        axisLine: {
          show: false,
          lineStyle: {
            color: ThemeColor.chartLineColor
          }
        },
        axisTick: {
          show: false
        },
        data: chartData.categories
      },
      series: [
        {
          name: '同比数据',
          type: 'bar',
          data: chartData.countThree, // 数据全为0，不显示柱子
          itemStyle: {
            color: 'transparent' // 透明柱子
          },
          barWidth: '1px',
          label: {
            show: true,
            position: 'right',
            formatter: function (params) {
              const index = params.dataIndex;
              const rate = chartData.ratioData[index];
              if (rate > 0) {
                return '{a| ' + `增长↑: ${rate}%` + '}';
              } else {
                return '{b| ' + `下降↓: ${Math.abs(rate)}%` + '}';
              }
            },
            rich: {
              a: {
                color: '#FFC900',
                align: 'center',
                fontWeight: 'bold',
                backgroundColor: 'rgba(255, 255, 255, 0.1)',
                borderRadius: 6,
                lineHeight: 28,
                padding: [4, 3, 4, 3],
                width: 90
              },
              b: {
                color: '#ffffff',
                align: 'center',
                fontWeight: 'bold',
                backgroundColor: 'rgba(255, 255, 255, 0.1)',
                borderRadius: 6,
                lineHeight: 28,
                padding: [4, 3, 4, 3],
                width: 90
              }
            },
            fontWeight: 'bold',
            offset: [24, 12] // 文字偏移，避免与其他标签重叠
          }
        },
        {
          name: '数量',
          type: 'bar',
          data: chartData.countOne,
          itemStyle: {
            borderRadius: [5, 5, 5, 5],
            color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
              {
                offset: 0,
                color: '#2352CC'
              },
              {
                offset: 0.5,
                color: '#3CB6FF'
              },
              {
                offset: 1,
                color: '#94D4FF'
              }
            ])
          },
          label: {
            show: true,
            position: 'right',
            color: '#ffffff',
            formatter: '{c}'
          }
        },
        {
          name: '数量',
          type: 'bar',
          data: chartData.countTwo,
          itemStyle: {
            borderRadius: [5, 5, 5, 5],
            color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
              {
                offset: 0,
                color: '#eed15d'
              },
              {
                offset: 0.5,
                color: '#d1d4d4ff'
              },
              {
                offset: 1,
                color: '#f0f5f7ff'
              }
            ])
          },
          label: {
            show: true,
            position: 'right',
            color: '#ffffff',
            formatter: '{c}'
          }
        }
      ]
    };
    return option;
  }

  /**
   * 初始化图表
   * @param container 图表容器id
   */
  function initChart(initData?: any): any {
    if (!container.value) return;
    chartData = initData;
    const option: EChartsOption = getOption();
    chartRef.value = echarts.init(container.value);
    chartRef.value && chartRef.value.setOption(option);

    // 添加自动轮播功能
    if (chartRef.value && option.series?.length > 0) {
      const { start, stop } = useAutoTooltip(chartRef.value as unknown as any, {
        interval: 2500,
        seriesIndex: 0
      });

      // 延迟启动，确保图表渲染完成
      setTimeout(() => {
        start();
      }, 1000);

      // 存储停止函数，供组件卸载时调用
      chart.stopTooltip = stop;
      return stop;
    }
  }

  /**
   * @description 重新set一下resize后的字体 不然会有偏移
   */
  function resetFontSize() {
    const option = getOption();
    // option.yAxis.data = xAxisPreData.value?.length ? xAxisPreData.value : option.yAxis.data;
    // 需要重新计算字体不然依旧会有点偏差
    chartRef.value && chartRef.value.setOption(option);
  }

  /**
   * @description 处理图表resize
   */
  function resizeChart() {
    if (chartRef.value) {
      handleChartResize(chartRef.value);
      resetFontSize();
    }
  }

  return {
    chart,
    container,
    chartRef,
    getOption
  };
}
